from itsdangerous import TimedJSONWebSignatureSerializer as TJSWSerializer
from django.conf import settings

# 生成加密的url链接地址方法
from users.models import User


def generate_verify_url(user):
    dict_data = {"user_id": user.id, "email": user.email}

    serializer = TJSWSerializer(secret_key=settings.SECRET_KEY, expires_in=60*30)

    token = serializer.dumps(dict_data)

    verify_url = "%s?token=%s" % (settings.EMAIL_VERIFY_URL, token.decode())

    return verify_url

# 解密
def decode_token(token):

    serializer = TJSWSerializer(secret_key=settings.SECRET_KEY, expires_in=60*30)

    try:
        dict_data = serializer.loads(token)
        user_id = dict_data.get("user_id")
        user = User.objects.get(id=user_id)

    except Exception:
        return None

    return user

